//
//  NetworkManager+Error.swift
//  Kosspot
//
//  Created by 胡辉 on 2025/6/29.
//

import Foundation
import Moya
import RxSwift


extension PrimitiveSequence where Trait == SingleTrait, Element == Response {
    func handleNetworkError() -> Single<Element> {
        return self.catch { error in
            let moyaError = error as? MoyaError
            let networkError: NetworkError
            
            switch moyaError {
            case .statusCode(let response):
                switch response.statusCode {
                case 401:
                    networkError = .unauthorized
                case 400...499:
                    networkError = .invalidResponse(statusCode: response.statusCode)
                case 500...599:
                    networkError = .requestFailed(description: "服务器内部错误")
                default:
                    networkError = .serverError(code:response.statusCode, message: "未知错误")
                }
            case .underlying(let underlyingError, _):
                networkError = .requestFailed(description: underlyingError.localizedDescription)
            default:
                networkError = .serverError(code: 10000, message: "网络连接失败")
            }
            
            return .error(networkError)
        }
    }
}

